package com.zx.znav.controller.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.znav.bean.Link;
import com.zx.znav.bean.LinkTag;
import com.zx.znav.bean.Navigation;
import com.zx.znav.bean.Tag;
import com.zx.znav.constant.Constants;
import com.zx.znav.controller.vo.LinkVO;
import com.zx.znav.error.BusinessException;
import com.zx.znav.error.EnumBusinessError;
import com.zx.znav.response.CommonReturnType;
import com.zx.znav.service.LinkService;
import com.zx.znav.service.LinkTagService;
import com.zx.znav.service.NavigationService;
import com.zx.znav.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 后台链接管理
 * @since 2023-07-21 10:07
 */
@Controller
@RequestMapping("/admin/link")
public class LinkController {
    @Autowired
    private LinkService linkService;
    @Autowired
    private NavigationService navigationService;
    @Autowired
    private LinkTagService linkTagService;
    @Autowired
    private TagService tagService;

    @RequestMapping
    public String index(Model model){
        //查数据
        //一级导航
        List<Navigation> firstNavigation = navigationService.listFirstNavigation();
        //二级导航
        List<Navigation> secondNavigation = navigationService.listSecondNavigation();
        //标签数据
        List<Tag> tags = tagService.listTags();
        //分页链接数据
        Page<Link> linkPage = linkService.pageLink(new Link(), 1, Constants.SHOW_LINK_PAGE_SIZE);
        model.addAttribute(Constants.FIRST_NAVIGATION_KEY, firstNavigation);
        model.addAttribute(Constants.SECOND_NAVIGATION_KEY, secondNavigation);
        model.addAttribute(Constants.TAG_KEY, tags);
        //前端需要导航名称
        model.addAttribute(Constants.LINK_PAGE_KEY, convert(linkPage));
//        model.addAttribute(Constants.LinK_KEY, links);
        return "admin/link";
    }
    private Page<LinkVO> convert(Page<Link> page){
        Page<LinkVO> linkVOPage = new Page<>();
        BeanUtils.copyProperties(page, linkVOPage);
        //Link -> LinkVO
        linkVOPage.setRecords(page.getRecords().stream().map(this::convert).collect(Collectors.toList()));
        return linkVOPage;
    }

    private LinkVO convert(Link link){
        LinkVO linkVO = new LinkVO();
        BeanUtils.copyProperties(link, linkVO);
        //查标签
        List<LinkTag> linkTags = linkTagService.listByLinkId(link.getId());
        linkVO.setTagIds(linkTags.stream().map(LinkTag::getTagId).collect(Collectors.toList()));
        //查导航名称
        linkVO.setFirstNavName(navigationService.getById(link.getFirstNavId()).getName());
        linkVO.setSecondNavName(navigationService.getById(link.getSecondNavId()).getName());
        return linkVO;
    }
    //查找
    @RequestMapping("/get")
    @ResponseBody
    public Object get(Integer id){
        return CommonReturnType.create(convert(linkService.getById(id)));
    }

    @RequestMapping("/list")
    @ResponseBody
    public Object list(){
        return CommonReturnType.create(linkService.listLink());
    }

    //添加
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public Object add(Link link, String[] tagIds) throws BusinessException {
        try {
            if(link.getIcon() == null || link.getIcon().equals("")){ //使用网址API获取图标链接
                link.setIcon(Constants.REQUEST_API + handlerUrl(link.getUrl()) + ".png");
            }
            linkService.save(link);
            //保存链接和标签关系
            linkTagService.saveBatch(getLinkTagList(link.getId(), tagIds));
        } catch (Exception e) { //SQL 异常
            e.printStackTrace();
            throw new BusinessException(EnumBusinessError.NAME_EXISTS);
        }
        return CommonReturnType.create(link);
    }
    private String handlerUrl(String url){
        //https://www.bilibili.com/ ->www.bilibili.com
        return url.substring(8, url.length() - 1);
    }
    private List<LinkTag> getLinkTagList(Integer linkId, String[] tagIds){
        List<LinkTag> linkTagList = new ArrayList<>();
        for(String tagId : tagIds){
            LinkTag linkTag = new LinkTag();
            linkTag.setLinkId(linkId);
            linkTag.setTagId(Integer.parseInt(tagId));
            linkTagList.add(linkTag);
        }
        return linkTagList;
    }

    //修改
    @PutMapping("/update")
    @Transactional
    @ResponseBody
    public Object update(Link link, String[] tagIds) throws BusinessException {
        try {
            linkService.updateById(link);
            //修改链接和标签关系

            //先删除所有linkId对应的数据
            linkTagService.deleteAllByLinkId(link.getId());
            //保存链接和标签关系
            linkTagService.saveBatch(getLinkTagList(link.getId(), tagIds));
        } catch (Exception e) { //SQL 异常
            e.printStackTrace();
            throw new BusinessException(EnumBusinessError.NAME_EXISTS);
        }
        return CommonReturnType.create(link);
    }
    //删除
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public Object delete(@PathVariable Integer id){
        linkService.removeById(id);
        //删除链接和标签关系
        linkTagService.deleteAllByLinkId(id);
        return CommonReturnType.create("删除成功");
    }

    //分页搜索
    @GetMapping("/search")
    @ResponseBody
    public Object search(Link link, Integer pageNo, Integer pageSize){
        return CommonReturnType.create(convert(linkService.pageLink(link, pageNo, pageSize)));
    }
}
